package fun.codedesign.jdk.socket.bio;


import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * 收到的socket连接只能accept一次，然后进行执行，如果要复用，需要建立连接后循环读取消息
 * 对消息可以进行分割符的区分。比如一个字节一个字节的读取，读取到分割符之后组装第一个请求
 * 依次
 *
 * @author zengjian
 * @create 2018-04-17 9:00
 * @since 1.0.0
 */
public class BioServer {

    private ServerSocket serverSocket;
    private volatile boolean start;
    private static Set<Socket> socketCache = new HashSet<>();
    private boolean loopHandle = true;

    public BioServer() {
        try {
            serverSocket = new ServerSocket(8080);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        if (start) {
            return;
        }
        System.out.format("服务器已启动,host：%s port: %d", "localhost", 8080);
        start = true;
        while (start) {
            try {
                Socket socket = serverSocket.accept();
                handle(socket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void stop() {
        this.start = false;
    }

    private void handle(Socket socket) throws IOException {
        // 缓存该socket然后持续读该通道的数据
        if (!socketCache.contains(socket)) {
            socketCache.add(socket);
        }
        while (loopHandle) {
            String req = getInputStream(socket);
            System.out.println("接收到请求:" + req);
            socket.getOutputStream().write(("服务器:你的请求我已接收到!,现在日期是:" + new Date()).getBytes("utf-8"));
            socket.getOutputStream().flush();
        }
    }

    public static String getInputStream(Socket socket) throws IOException {
        InputStream is = socket.getInputStream();
        byte[] bytes = new byte[is.available()];
        is.read(bytes);
        String input = new String(bytes, "utf-8");
        return input;
    }

    public static void main(String[] args) {
        BioServer server = new BioServer();
        server.start();
    }
}
